package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import modle.Player;
import modle.Table;

import com.google.gson.Gson;

import flex01.SocketServer;
/**
 * 用来获取用户进入的房间的  所有桌子列表
 * @author GaoTong
 * @date 2013/01/02
 * @modify 2013/1/5 增加获取玩家列表的数据
 */
public class GetTablesServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/javascript;charset=utf-8");
		PrintWriter out = response.getWriter();
		 response.setCharacterEncoding("utf-8");
		//得到用户请求的房间号
		int RoomIndex = Integer.parseInt(request.getParameter("selectedRoom"));
		//得到房间的类型
		char type = request.getParameter("type").charAt(0);
		SocketServer server = StartSocketServlet.socketServerList.get(RoomIndex);
		Gson gson = new Gson();
		//如果是固定的房间列表
		
		Table tables[] = null;
		if(type == 'F'){
			tables = new Table[50];
			
			//先生成空的桌子
			for(int i=0; i<tables.length; i++){
				tables[i] = new Table();
				tables[i].setName("罗马战棋");
			}
			for(int i=0; i<server.clientList.size(); i++){
				Player p = server.clientList.get(i);
				if(p.getTablePosition() >= 0){ //说明此用户坐下了
					int pos = p.getTablePosition();
					if(pos%2 == 0)
						tables[pos/2].setPlayer1(p.getName());
					else
						tables[pos/2].setPlayer2(p.getName());
				}
			}
			
			//返回结果JSON
//			out.println(gson.toJson(tables));
//			System.out.println(gson.toJson(tables));
			
		}else{ //如果桌子是动态生成的
			
				tables = new Table[server.tableMap.size()];
				
				//先生成空的桌子
				for(int i=0; i<tables.length; i++){
					tables[i] = server.tableMap.get(i);
				}

		}
		
//		Object[] data = new Object[2];
//		
//		
//		Player players[] = new Player[server.clientList.size()];
//		for(int i=0; i<players.length; i++){
//			
//			players[i] = new Player();
//			players[i].setName(server.clientList.get(i).getName());
//			players[i].setTablePosition(server.clientList.get(i).getTablePosition());
//		}
//		
//		data[0] = tables;
//		data[1] = players;
		
		out.println(gson.toJson(tables));
		System.out.println("tables and players:" + gson.toJson(tables));
		out.flush();
		out.close();
	}

}
